<?php
namespace app\controllers;

use app\models\AdRecorder;

class AdController extends BaseController{
    public function actionAdd(){
        $post = \Yii::$app->request->post();
        $id = intval($post['AdRecorder']['id']);
        if($id){
            $model = AdRecorder::find()->where('id=:id',[':id' => $id])->one();
            if(!$model){
                $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
                return json_encode($result);
            }
        }else{
            $model = new AdRecorder();
            $model->addtime = time();
        }
        $result = $model->add($post);
        return json_encode($result);
    }

    public function actionList(){
        $list = AdRecorder::find();
        $list = $list->orderBy('ad_order DESC')->asArray()->all();
        foreach($list as $k=>$v){
            $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            $list[$k]['thumb_pic'] = str_replace('../',\Yii::$app->params['pic_url'],$v['thumb_pic']);
        }
        $result = ['result'=>1,'data'=>$list];
        return json_encode($result);
    }

    public function actionOne(){
        $id = \Yii::$app->request->post('id');
        $model = AdRecorder::find()->where('id=:id',[':id' => $id])->asArray()->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model['thumb_pic']=empty($model['thumb_pic'])?'':str_replace("../",\Yii::$app->params['pic_url'],$model['thumb_pic']);
        $result = ['result'=>1,'data'=>$model];
        return json_encode($result);
    }

    public function actionDel(){
        $id = \Yii::$app->request->post("id");
        $model = AdRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $model->delete();
        $result = ['result'=>1,'data'=>'操作成功'];
        return json_encode($result);
    }
}